import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

class Solution {
    public int[] index;
    public int n;
    public int m;
    public int cutOffTree(List<List<Integer>> forest) {
        PriorityQueue<Integer> queue=new PriorityQueue<>();
        n=forest.size();
        m=forest.get(0).size();
        for (List<Integer> integers : forest) {
            for (int x:integers) {
                if(x>1){
                    queue.add(x);
                }
            }
        }
        int len=queue.size();
        int ans=0;
        index=new int[2];
        while(len--!=0){
            int t=queue.poll();
            int tt=bfs(t,forest);
            if(tt==-1){
                return -1;
            }
            ans+=tt;
        }
        return ans;
    }
    public int[] dx={1,0,-1,0};
    public int[] dy={0,1,0,-1};
    public int bfs(int target,List<List<Integer>> forest){
        if(target==forest.get(index[0]).get(index[1])){
            return 0;
        }
        Queue<int[]> queue=new LinkedList<>();
        boolean[][] vis=new boolean[n][m];

        queue.add(new int[]{index[0],index[1]});
        vis[index[0]][index[1]]=true;
        int step=0;

        while(!queue.isEmpty()){
            int sz= queue.size();
            step++;
            for (int i = 0; i < sz; i++) {
                int[] arr=queue.poll();
                for (int j = 0; j < 4; j++) {
                    int x=dx[j]+arr[0];
                    int y=dy[j]+arr[1];
                    if(x>=0 && x<n && y>=0 && y<m && forest.get(x).get(y)!=0 && !vis[x][y]){
                        if(forest.get(x).get(y)==target){
                            index[0]=x;
                            index[1]=y;
                            return step;
                        }
                        queue.add(new int[]{x,y});
                        vis[x][y]=true;
                    }
                }
            }
        }
        return -1;
    }
}